﻿#include "SingleLinkedListWithHead.h"

// 带头单链表-工具函数
// 动态申请节点
ListNode* BuyListNode(DataType elem)
{
	ListNode* node = (ListNode*)malloc(sizeof(ListNode));
	if (node == NULL)
	{
		printf("malloc error\n");
		exit(-1);
	}
	node->data = elem;
	node->next = NULL;
	return node;
}


// 带头单链表-基本操作函数
// 带头单链表初始化
void SingleHeadListInit(ListNode** list)
{
	assert(list);
	(*list) = BuyListNode(0);
}
// 带头单链表头部插入
void SingleHeadListPushFront(ListNode* list, DataType elem)
{
	assert(list);
	ListNode* node = BuyListNode(elem);
	node->next = list->next;
	list->next = node;
}
// 带头单链表头部删除
void SingleHeadListPopFront(ListNode* list)
{
	assert(list);
	assert(list->next != NULL);
	ListNode* del = list->next;
	list->next = del->next;
	free(del);
}
// 带头单链表尾部插入
void SingleHeadListPushBack(ListNode* list, DataType elem)
{
	assert(list);
	ListNode* node = BuyListNode(elem);
	ListNode* cur = list;
	while (cur->next)
	{
		cur = cur->next;
	}
	cur->next = node;
}
// 带头单链表尾部删除
void SingleHeadListPopBack(ListNode* list)
{
	assert(list);
	assert(list->next);
	ListNode* prev = list;
	ListNode* cur = list->next;
	while (cur->next)
	{
		prev = cur;
		cur = cur->next;
	}
	free(cur);
	prev->next = NULL;
}
// 带头单链表pos位置后插入x
void SingleHeadListInsertAfter(ListNode* list, size_t pos, DataType elem)
{
	assert(list);
	assert(pos < SingleHeadListLength(list));
	ListNode* cur = list->next;
	while (pos--)
	{
		cur = cur->next;
	}
	ListNode* node = BuyListNode(elem);
	node->next = cur->next;
	cur->next = node;
}
// 带头单链表删除pos位置后元素
void SingleHeadListEraseAfter(ListNode* list, size_t pos)
{
	assert(list);
	assert(pos < SingleHeadListLength(list) - 1);
	ListNode* cur = list->next;
	while (pos--)
	{
		cur = cur->next;
	}
	ListNode* del = cur->next;
	cur->next = del->next;
	free(del);
}
// 带头单链表查找元素 - 返回对应元素节点
ListNode* SingleHeadListFind(ListNode* list, DataType data)
{
	assert(list);
	ListNode* cur = list->next;
	while (cur != NULL)
	{
		if (cur->data == data)
		{
			return cur;
		}
		cur = cur->next;
	}
	return NULL;
}
// 带头单链表长度
size_t SingleHeadListLength(ListNode* list)
{
	assert(list);
	int len = 0;
	ListNode* cur = list->next;
	while (cur != NULL)
	{
		len++;
		cur = cur->next;
	}
	return len;
}
// 带头单链表单链表
void SingleHeadListTraverse(ListNode* list)
{
	assert(list);
	ListNode* cur = list->next;
	while (cur != NULL)
	{
		printf("%d->", cur->data);
		cur = cur->next;
	}
	printf("NULL\n");
}